<!-- AI模板 -->
<template>
  <div class="dashboard-editor-container">
    <div class="xxx" style="margin-top: 10px;">
      <div style="display:flex;justify-content:space-between;">
        <partitionTree :nodeData="nodeData" :addTemplate="false" @handleNodeClick="handleNodeClick" ref="partitionTree" @toggleVisibility="toggleVisibility"></partitionTree>
        <div :style="{ width:containerWidth}"  class="box" style="background:#fff;padding:20px;border: 1px solid #ddd;border-radius: 4px;box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.1);">
          <el-button type="primary" @click="addModer">添加校区</el-button>
          <el-table stripe border :data="tableData" style="width: 100%; margin-top: 15px" height="640">
            <el-table-column label="序号" width="80" type="index" :index='(index) => { return (index + 1) + (pageNum - 1) * pageSize }'> </el-table-column>
            <el-table-column label="校区编码" prop="SchoolID" width="80" align="left" show-overflow-tooltip></el-table-column>
            <el-table-column label="校区名称" prop="SchoolName"  align="left" show-overflow-tooltip></el-table-column>
            <el-table-column label="所在分区" prop="PrimArea"  align="left" show-overflow-tooltip>
              <template slot-scope="{row}">
                <span>{{ row.PrimArea }} / {{ row.SecondArea }}</span>
              </template>
            </el-table-column>
            <el-table-column label="联系人" prop="Contact" width="100" align="left" show-overflow-tooltip></el-table-column>
            <el-table-column label="联系电话" prop="Phone" width="120" align="left" show-overflow-tooltip></el-table-column>
            <el-table-column label="联系邮箱" prop="EMail"  align="left" show-overflow-tooltip></el-table-column>
            <el-table-column label="地址" prop="Address"  align="left" show-overflow-tooltip></el-table-column>
            <el-table-column label="创建时间" prop="CreateTime" width="160px" align="left" show-overflow-tooltip></el-table-column>
            <el-table-column label="备注信息" prop="Descp"  align="left" show-overflow-tooltip></el-table-column>
            <el-table-column label="操作" width="170px" align="left" fixed="right" >
              <template slot-scope="scope">
                <el-button type="primary" size="mini" @click="changeModer(scope.row)">修改</el-button>
                <el-button size="mini" type="danger" @click="deleteModer(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination 
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" 
            :current-page=pageNum
            :page-size=pageSize
            background 
            layout="total, prev, pager, sizes, next, jumper"
            :total="total">
          </el-pagination>
        </div>
      </div>
    </div>
    <!-- 分区弹窗 -->
    <el-dialog 
      :close-on-click-modal="false" 
      :close-on-press-escape="false" 
      :visible.sync="moderVisible"
      :title="Action === 1 ? '添加校区' : '修改校区'" 
      v-el-drag-dialog @close="Moder = {}" width="30%">
      <el-form label-width="100px" :rules="rules" :model="Moder" ref="Moder">
        <el-form-item label="校区编码：" prop="SchoolID">
          <el-input placeholder="请输入校区编码" maxlength="16" :disabled="Action === 2" v-model="Moder.SchoolID"></el-input>
        </el-form-item>
        <el-form-item label="校区名称：" prop="SchoolName">
          <el-input placeholder="请输入校区名称" maxlength="16" :disabled="Action === 2" v-model.trim="Moder.SchoolName"></el-input>
        </el-form-item>
        <el-form-item label="所在分区：" prop="PrimArea">
          <el-cascader
            ref="cascaderAddr"
            style="width:100%;"
            v-model="Moder.PrimArea"
            placeholder="请选择分区"
            clearable
            :options="nodeData"
            :props="{ expandTrigger: 'hover', label: 'Name', value: 'Name', children:'Children'}"
            @change="handleChange">
          </el-cascader>
        </el-form-item>
        <el-form-item label="硬件标识" prop="HardID">
          <el-input placeholder="请输入硬件标识" maxlength="16" :disabled="Action === 1" v-model="Moder.HardID"></el-input>
        </el-form-item>
        <el-form-item label="联系人：" prop="Contact">
          <el-input placeholder="请输入联系人" maxlength="16" v-model.trim="Moder.Contact"></el-input>
        </el-form-item>
        <el-form-item label="联系电话：" prop="Phone">
          <el-input placeholder="请输入联系电话" oninput ="value=value.replace(/[^0-9-]/g,'')" v-model="Moder.Phone"></el-input>
        </el-form-item>
        <el-form-item label="联系邮箱：" prop="EMail">
          <el-input placeholder="请输入联系邮箱" maxlength="32" v-model="Moder.EMail"></el-input>
        </el-form-item>
        <el-form-item label="地址：" prop="Address">
          <el-input placeholder="请输入地址" maxlength="64" v-model="Moder.Address"></el-input>
        </el-form-item>
        <el-form-item label="备注信息：" prop="Descp">
          <el-input placeholder="请输入备注" type="textarea" :rows="3"  v-model="Moder.Descp"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit()">确 定</el-button>
        <el-button type="info" @click="moderVisible = false, reSource = [], $set(reSource, 'isSelected', false)">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Cookies from 'js-cookie'
import { connrequest } from '@/api/firstPage'
import { parseTime, getuuid, recursiveGetNodePath, recursiveGetChildNodePath } from '@/utils/index'
import elDragDialog from "@/directive/el-drag-dialog"; 
import partitionTree from "@/components/partitionTree"; 
export default {
  directives: { elDragDialog },
  components: {
    partitionTree
  },
  data() {
    return {
      pageNum: 1,
      pageSize: 10,
      total: 0,
      containerWidth: 'calc(100% - 240px)',
      tableData: [],
      nodeData: [],
      Action: 1,
      Moder: {},
      moderVisible: false,
      reSource: [],
      partitionList: [],
      choseArea: {},
      rules:{
        SchoolID: [
          {required: true, message: '请选择校区编码', trigger: 'blur'}
        ],
        SchoolName: [
          {required: true, message: '请选择校区名称', trigger: 'blur'}
        ],
        PrimArea: [
          {required: true, message: '请选择上级分区', trigger: 'change'}
        ],
        SecondArea: [
          {required: true, message: '请输入分区名称', trigger: 'blur'}
        ],
        AreaCode: [
          {required: true, message: '请输入分区编码', trigger: 'blur'}
        ],
        Contact: [
          {required: true, message: '请输入联系人', trigger: 'blur'}
        ],
        Phone: [
          {required: true, message: '请输入联系电话', trigger: 'blur'},
          // {
          //   validator: function(rule, value, callback) {
          //     if (/^1[34578]\d{9}$/.test(value) == false && value) {
          //       callback(new Error("手机号格式错误"));
          //     } else {
          //       callback();
          //     }
          //   },
          //   trigger: "blur"
          // }
        ],
        EMail:[
          {
          validator: function(rule, value, callback) {
              if (/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/i.test(value) == false  && value) {
                callback(new Error("邮箱格式错误"));
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ]
      }
    }
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.pageSize = Cookies.get('DefaultPageLength') * 1
    this.getData()
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
  },
  methods: {
    async getData() {
      const res = await connrequest('GetSchoolStatusSumTree')
      let partitionList = []
      res.Data.PrimName = res.Data.RootName //因为后端返回的所有分区名字叫RootName，子菜单又叫PrimAreaName, 这里做个转换
      this.RootName = res.Data.RootName
      res.Data.disabled = true
      res.Data.edit = false
      res.Data.PrimArea.map(item => {
        item.edit = false
        partitionList.push(item)
      })
      this.nodeData = [this.transformData(res.Data)]
      this.partitionList = partitionList
      this.GetDictArea(this.choseArea)
    },
    transformData(inputData) {
      const { RootName, OffLineCount, OnlineCount, PrimArea} = inputData;
        return {
          Name: RootName,
          level: 1,
          Count: `${OnlineCount + OffLineCount}`,
          Children: PrimArea.map(area => ({
            Name: area.PrimAreaName,
            Count: `${area.OnlineCount + area.OffLineCount}`,
            level: 2,
            Children: area.SecondArea.map(secondArea => ({
              Name: secondArea.SecondAreaName,
              Count: `${secondArea.OnlineCount + secondArea.OffLineCount}`,
              level: 3,
              onlineCount: secondArea.OnlineCount,
              offLineCount: secondArea.OffLineCount
          }))
        }))
      }
    },
    async GetDictArea(obj){
      const data = {
        Paging:{
          QueryPageNo: this.pageNum,
          QueryPageLength: this.pageSize
        },
        Filter:{
          PrimArea: '',
          SecondArea: "",
          SchoolName: "",
          Status: 0,
          OrderBy: "",
          ...obj
        }
      }
      const res = await connrequest('GetSchool', data)
      res.Data.map(item => {
        item.CreateTime = parseTime(item.CreateTime)
      })
      this.tableData = res.Data
      this.total = res.Paging.TotalCount
    },
    handleNodeClick(nodeData){
      const {node} = nodeData
      let arr = node.level === 1 ? recursiveGetChildNodePath(node, []) : recursiveGetNodePath(node, [])
      let obj = {}
      node.level === 1 ? '' : node.level === 2 ? obj.PrimArea = node.data.Name : obj.SecondArea = node.data.Name
      this.choseArea = obj
      this.PrimArea = arr
      this.$set(this.Moder, 'PrimArea', arr)
      this.GetDictArea(this.choseArea)
    },
    handleChange(node){
      // console.log(node);
    },
    addModer(){
      let arr = [this.nodeData[0].Name, this.nodeData[0].Children[0].Name, this.nodeData[0].Children[0].Children[0].Name] // 赶时间写的，后续需要修改
      this.Action = 1
      this.Moder = {
        SchoolID: getuuid(),
        PrimArea: this.PrimArea || arr
      }
      this.$nextTick(() => {
        this.$refs.Moder.clearValidate();
      })
      this.moderVisible = true
    },
    changeModer(row){
      this.Action = 2
      this.Moder = {...row, PrimArea:[this.RootName, row.PrimArea, row.SecondArea]}
      this.$nextTick(() => {
        this.$refs.Moder.clearValidate();
      })
      this.moderVisible = true
    },
    deleteModer(row){
      this.$confirm('此操作将永久删除该校区, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const data = {
          Data: {
            Action: 3,
            Detail: {...row}
          }
        }
        const res = await connrequest('EditSchool', data)
        if(res.Status.StatusCode === 0){
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.getData()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    },
    async submit(){
      this.$refs['Moder'].validate(async (valid) => {
        if (valid) {
          const data = {
            Data: {
              Action: this.Action,
              Detail: {
                SchoolID: this.Moder.SchoolID,
                PrimArea: this.Moder.PrimArea[1],
                SecondArea: this.Moder.PrimArea[2],
                SchoolName: this.Moder.SchoolName,
                Contact: this.Moder.Contact,
                Phone: this.Moder.Phone,
                EMail: this.Moder.EMail,
                Address: this.Moder.Address,
                Descp: this.Moder.Descp
              }
            }
          }
          const res = await connrequest('EditSchool', data)
          if(res.Status.StatusCode === 0){
            this.$message.success(this.Action === 1 ? '新增成功' : '修改成功')
            this.moderVisible = false
            this.getData()
          }
        }
      })
    },
    handleSizeChange(pageSize){
      this.pageSize = pageSize
      this.pageNum = 1
      this.GetDictArea(this.choseArea)
    },
    handleCurrentChange( pageNum ){
      this.pageNum = pageNum
      this.GetDictArea(this.choseArea)
    },
    toggleVisibility(isHidden) {
      if(isHidden)
        this.containerWidth = '100%';
      else 
        this.containerWidth = 'calc(100% - 240px)';
    },
  }
};
</script>
<style scoped>
.box {
  background-color: lightblue;
  transition: width 0.5s; /* 添加过渡动画 */
}

</style>
